package com.nettyServer.protoHandler;

import com.nettyServer.handler.Constants;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * @program: SpringBootDemos
 * @description:
 * @author: Kangsen
 * @create: 2022-08-02 16:39
 *
 * 编码器
 **/
@Slf4j
public class ProtobufEncoder extends MessageToByteEncoder {

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        // 将发送的消息对象转换为byte数组
        //byte[] bytes = msg.toByteArray();
        /** msg 转 byte[] **/
        ByteArrayOutputStream byteArrayOutputStream =new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(msg);
        byte[] bytes = byteArrayOutputStream.toByteArray();

        // 读取 ProtoMsg 消息的长度
        int length = bytes.length;
        ByteBuf buf = Unpooled.buffer(2 + length);
        // 先将消息协议的版本写入，也就是消息头
        buf.writeShort(Constants.PROTOCOL_VERSION);
        // 再将 ProtoMsg 消息的长度写入
        buf.writeShort(length);
        // 写入 ProtoMsg 消息的消息体
        buf.writeBytes(bytes);
        //发送
        out.writeBytes(buf);
    }

    public static void main(String[] args) {
        try {
            String str = "abcd";
            ByteArrayOutputStream byteArrayOutputStream =new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(str);
            byte[] bytes = byteArrayOutputStream.toByteArray();
            log.warn("bytes:{}",bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
